<template>
  <div class='search-box'>
    <form action="/">
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" background="#3296FA" @search="onSearch"
        @cancel="$router.go(-1)" @focus='isShowSearchResults=false' />
    </form>
    <!-- 搜索结果 -->
    <SearchResults :value='searchText' v-if='isShowSearchResults'></SearchResults>
    <!-- 搜索历史 -->
    <SearchHistory :history='history' v-else-if='!searchText' @search='onSearch'></SearchHistory>
    <!-- 搜索建议 -->
    <SearchSuggestion @search='onSearch' :value='searchText' v-else></SearchSuggestion>
  </div>
</template>

<script>
// 搜索历史组件
import SearchHistory from './components/search-history.vue'
// 搜索建议组件
import SearchSuggestion from './components/search-suggestion.vue'
// 搜索结果组件
import SearchResults from './components/search-results.vue'
// 本地获取数据 本地存储数据
import { getItem, setItem } from '@/utils/storage.js'
// 搜索历史的本地名
const HMTT_HISTORY = 'hmtt_history'
export default {
  data () {
    return {
      // 搜索框输入内容
      searchText: '',
      // 是否显示搜索结果
      isShowSearchResults: false,
      // 搜索历史
      history: getItem(HMTT_HISTORY) || []
    }
  },
  methods: {
    // 回车后触发
    onSearch (item) {
      // const index = this.history.findIndex(val => val === item)
      // if (index !== -1) { this.history.splice(index, 1) }
      // 存储搜索历史
      this.history.unshift(item)
      this.history = [...new Set(this.history)]
      this.searchText = item
      this.isShowSearchResults = true
    }
  },
  computed: {},
  // 本地存储
  watch: {
    history (val) {
      setItem(HMTT_HISTORY, val)
    }
  },
  filters: {},
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResults
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.search-box {
  // .van-search {
  //   position: fixed;
  //   top: 0;
  //   z-index: 2;
  // }
  .van-search__action {
    color: #fff;
  }
}
</style>
